<template>
  <!-- 表单搜索 -->
  <div class="user-header">
    <el-button type="primary" @click="handleAdd">+新增</el-button>
    <el-form :inline="true" :model="formInline">
      <el-form-item label="请输入">
        <el-input v-model="formInline.keyword" placeholder="请输入名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 表格数据 -->
  <div class="table">
    <el-table :data="list" style="width: 100%;height: 500px;">
      <el-table-column v-for="item in tableLabel" :key="item.prop" :label="item.label" :prop="item.prop"
        :width="item.width ? item.width : 125" />

      <el-table-column fixed="right" label="操作你" min-width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelet(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination background layout="prev, pager, next" :total="config.total" @current-change="changePage"
      class="pager" />
  </div>
  <!-- 弹出框 -->
  <el-dialog v-model="dialogVisible" :title="action === 'add' ? '新增' : '编辑'" width="40%" :before-close="handleClose">
    <!-- 弹出的表格 -->
    <el-form :inline="true" :model="formUser" ref="userForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '姓名是必填项' }]">
            <el-input v-model="formUser.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age"
            :rules="[{ required: true, message: '年龄必填' }, { type: 'number', message: '年龄是必填数字' }]">
            <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex" :rules="[{ required: true, message: '性别必选' }]">
            <el-select v-model="formUser.sex" placeholder="请选择性别">
              <el-option label="男" value="0" />
              <el-option label="女" value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="日期" prop="birth" :rules="[{ required: true, message: '日期必选' }]">
            <el-date-picker v-model="formUser.birth" type="date" label="出生日期" placeholder="请输入出生日期"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="地址" prop="addr" :rules="[{ required: true, message: '地址必选' }]">
          <el-input v-model="formUser.addr" placeholder="请输入地址" />
        </el-form-item>
      </el-row>
      <el-form-item>
        <el-button @click="hanleCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">
          确定
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 弹出的表格 -->
    <!-- <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogVisible = false">
          确定
        </el-button>
      </div>
    </template> -->
  </el-dialog>
</template>

<script setup>

import { getCurrentInstance, onMounted, ref, reactive } from 'vue';
const list = ref([])
const { proxy } = getCurrentInstance();
//得到表格数据
const getUserData = async (config) => {
  let res = await proxy.$api.getUser(config)
  console.log(res);
  config.total = res.count
  //渲染表格数据 因为传来性别参数是sex 与表格参数不对应 需要修改
  list.value = res.list.map((item) => {
    item.sexLabel = item.sex === 0 ? '女' : '男'
    return item
  })
}
//表头数据
const tableLabel = reactive([
  {
    prop: "name",
    label: "姓名",
  },
  {
    prop: "age",
    label: "年龄",
  },
  {
    prop: "sexLabel",
    label: "性别",
  },
  {
    prop: "birth",
    label: "出生日期",
    width: 200,
  },
  {
    prop: "addr",
    label: "地址",
    width: 320,
  },
]);
//分页器数据
const config = reactive({
  total: 0,
  page: 1,
  name: ''
})
//点击分页器
const changePage = (page) => {
  //默认参数 得到点击的页码数
  config.page = page
  //重新得到对应页码数的数据
  getUserData(config)
  console.log(page);
}
onMounted(() => {

  getUserData(config)

})

const formInline = reactive({
  keyword: ''
})
//定义搜索方法，点击后修改数据传给后端
const handleSearch = () => {
  config.name = formInline.keyword;
  getUserData(config)
}
//弹出框控制变量
const dialogVisible = ref(false)
//弹出框X按钮
const handleClose = (done) => {
  ElMessageBox.confirm('确定关闭吗')
    .then(() => {
      proxy.$refs.userForm.resetFields()
      done()
    })
    .catch(() => {
      // catch error
    })
}
//新增用户的form数据
let formUser = reactive({
  sex: undefined,
  age: undefined,
  name: undefined,
  addr: undefined,
  birth: undefined
})
//定义一个格式化时间的方法
const timeFormat = (time) => {
  var time = new Date(time)
  var year = time.getFullYear();
  var month = time.getMonth() + 1;
  var date = time.getDate();
  function add(m) {
    return m < 10 ? "0" + m : m;
  }
  return year + "-" + add(month) + "-" + add(date)
}

//定义确定的方法
const onSubmit = () => {
  //添加前需要校验表单内容 不通过不给添加
  proxy.$refs.userForm.validate(async (valid) => {
    //接收一个形参判断表单是否通过 通过就添加
    if (valid) {
      //判断是需要执行编辑还是新增操作
      if (action.value == "add") {
        //新增操作
        //请求前格式化一下日期
        formUser.birth = timeFormat(formUser.birth)
        let res = await proxy.$api.addUser(formUser)
        console.log(res, 'sum');
        //点击确定后重置标点
        if (res) {
          //调用重置方法 记得定义prop属性
          proxy.$refs.userForm.resetFields()
          //同时关闭对话框
          dialogVisible.value = false
          //重新加载也页面数据
          getUserData(config)
        }
      }else{
        //转换一下性别
        formUser.sex == '男' ? (formUser.sex = '1') : (formUser.sex = '0')
        //编辑操作 调用编辑接口
        let res = await proxy.$api.editUser(formUser)
        //点击确定后重置标点
        if (res) {
          //调用重置方法 记得定义prop属性
          proxy.$refs.userForm.resetFields()
          //同时关闭对话框
          dialogVisible.value = false
          //重新加载也页面数据
          getUserData(config)
        }
        
      }
    } else {
      //校验不通过报错
      ElMessage({
        showClose: true,
        message: '请你输入对内容',
        type: 'error'
      })
    }
  })

}

//点击取消的方法
const hanleCancel = () => {
  proxy.$refs.userForm.resetFields()
  //同时关闭对话框
  dialogVisible.value = false
}
//定义一个判断是新曾还是编辑的值
const action = ref('add')

//点击编辑方法
const handleEdit = (row) => {
  console.log(row);
  action.value = 'edit'
  //显示模态框
  dialogVisible.value = true
  //判断显示男女
  row.sex == 1 ? (row.sex = '男') : (row.sex = '女')
  //放在里面执行，防止点击编辑取消后点击新增出现数据
  proxy.$nextTick(() => {
    // 浅拷贝，把数据赋值上去
    Object.assign(formUser, row)
  })

}
//点击新增的方法
const handleAdd = () => {
  action.value = 'add'
  dialogVisible.value = true
}

//点击删除的方法
const handleDelet=(row)=>{
  //确认是否删除
  ElMessageBox.confirm('删除不')
    .then(async() => {
      //确认删除后调接口 传入id
      await proxy.$api.deleteUser({
        id:row.id
      })
      ElMessage({
        showClose:true,
        message:'删除成功',
        type:'success'
      })
      //重新加载也页面数据
      getUserData(config)
    })
    .catch(() => {
      // catch error
    })
}

</script>

<style lang="less" scoped>
.table {
  position: relative;
  height: 520px;

  .pager {
    position: absolute;
    right: 0;
    bottom: -20px;
  }
}

.user-header {
  display: flex;
  justify-content: space-between;
}
</style>